package com.xoa.service.hr.impl;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.hr.HrStaffInfoMapper;
import com.xoa.dao.hr.HrStaffLeaveMapper;
import com.xoa.dao.hr.HrStaffReinstatementMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.HrCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.hr.*;
import com.xoa.model.users.Users;
import com.xoa.service.hr.HrStaffLeaveService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 离职模块服务实现类
 */
@Service
public class HrStaffLeaveServiceImpl implements HrStaffLeaveService {
    @Resource
    HrStaffLeaveMapper hrStaffLeaveMapper;
    @Resource
    UsersMapper usersMapper;
    @Resource
    HrStaffInfoMapper hrStaffInfoMapper;
    @Resource
    HrStaffReinstatementMapper hrStaffReinstatementMapper;
    @Resource
    HrCodeMapper hrCodeMapper;


    private static ToJson<HrStaffLeave> toJson = new ToJson<HrStaffLeave>();

    private static final String HRSTAFFLEAVE = "hrStaffLeave";
    private static final String REINSTATEMENT = "reinstatement";

    /**
     * 创建作者：张丽军
     * 方法介绍：根据部门id查询离职人员信息
     * @param request
     * @param deptId
     * @return
     */
    @Override
    public ToJson<HrStaffInfo> querytLeavePersonByDeptId(HttpServletRequest request,Integer deptId) {
        ToJson<HrStaffInfo> toJson = new ToJson<HrStaffInfo>(1, "error");
        try {
            List<HrStaffInfo> list = hrStaffInfoMapper.selectLeavePersonByDeptId(deptId);
            for(HrStaffInfo hrStaffInfo:list){
                if(!StringUtils.checkNull(hrStaffInfo.getUserId())){
                    Users users=usersMapper.getUsersByuserId(hrStaffInfo.getUserId());
                    if(users!=null){
                        hrStaffInfo.setAvatar(users.getAvatar());
                    }
                }
                hrStaffInfo.setUserName(hrStaffInfo.getStaffName());
                HrStaffLeave hrStaffLeave= hrStaffLeaveMapper.queryStaffLeaveByLeavePerson(hrStaffInfo.getUserId());
                if(hrStaffLeave!=null){
                    hrStaffInfo.setLeaveReason(hrStaffLeave.getQuitReason());
                }
                if(StringUtils.checkNull(hrStaffInfo.getAvatar())){
                    hrStaffInfo.setAvatar(hrStaffInfo.getStaffSex());
                }
            }
            if (list.size() > 0) {
                toJson.setObject(list);
                toJson.setObj(list);
                toJson.setMsg("ok");
            } else {
                toJson.setObject(list);
                toJson.setObj(list);
                toJson.setMsg("离职人员信息为空");
            }
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 创建作者：张丽军
     * 方法介绍：根据部门Id查询离职人员名
     * @param request
     * @param deptId
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> getLeaveUsersByDeptId(HttpServletRequest request,Integer deptId) {
        ToJson<HrStaffLeave> toJson = new ToJson<HrStaffLeave>(1, "error");
        try {
            List<HrStaffLeave> list = hrStaffLeaveMapper.getLeaveUsersByDeptId(deptId);
            if (list.size() > 0) {
                toJson.setObj(list);
                toJson.setMsg("ok");
            } else {
                toJson.setObject("没数据");
                toJson.setMsg("离职人员为空");
            }
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 张丽军
     * 新建离职信息
     * @param hrStaffLeave
     * @param request
     * @return
     */
    @Override
    public  ToJson<HrStaffLeave>  addLeaveInfor(HrStaffLeave hrStaffLeave,HttpServletRequest request){
        initializeToJson(toJson);
        try {
            if(notNullOrEmpty(hrStaffLeave.getLeavePerson()) && notNullOrEmpty(hrStaffLeave.getLeaveDept())) {

                //由于数据库中字段都不能为空，所以要做一下判断和处理
                handleHrStaffLeaveInput(hrStaffLeave);

                //在session中获取用户名id和部门id
                Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
                Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
                hrStaffLeave.setCreateUserId(users.getUserId());
                hrStaffLeave.setCreateDeptId(users.getDeptId());

                //附件处理
                if (null!=hrStaffLeave.getAttachmentName() && !"".equals(hrStaffLeave.getAttachmentName())) {
                    List<Attachment> attachmentList = GetAttachmentListUtil.
                            returnAttachment(hrStaffLeave.getAttachmentName(), hrStaffLeave.getAttachmentId(), "xoa" + (String) request.
                                    getSession().getAttribute("loginDateSouse"), HRSTAFFLEAVE);
                    hrStaffLeave.setAttachmentList(attachmentList);
                }

                //计数器
                int count = 0;

                count += hrStaffLeaveMapper.addLeaveInfor(hrStaffLeave);//添加到离职信息表中

                //并将信息人事表中的状态改为离职
                //先从人事表中查出staffId
                HrStaffInfo hrStaffInfo = hrStaffInfoMapper.getStaffByUserId(hrStaffLeave.getLeavePerson());
                if (null!=hrStaffInfo) {
                    hrStaffInfo.setWorkStatus("02");
                    if (!"0000-00-00".equals(hrStaffLeave.getQuitTimeFact())) {
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                        int year= DateCompute.workAge(sdf.parse(hrStaffLeave.getQuitTimeFact()),sdf.parse( hrStaffInfo.getJobBeginning() == null ? "0000-00-00" : hrStaffInfo.getJobBeginning() ));
                        hrStaffInfo.setJobAge(String.valueOf(year));
                    }

                    count += hrStaffInfoMapper.updatePersonFile(hrStaffInfo);

                    //将原部门id(leaveDept)存入hr_staff_info表中的DEPT_ID字段中
                    hrStaffInfo.setDeptId(Integer.valueOf(hrStaffLeave.getLeaveDept()));
                    hrStaffLeaveMapper.updateHrStaffInfoDeptId(hrStaffInfo);
                }

                //修改用户表
                Users users1 = usersMapper.getUsersByuserId(hrStaffLeave.getLeavePerson());//先将要修改的用户信息查询出来，将部门编号改为0，代表用户离职
                if (null!=users1) {
                    users1.setDeptId(0);
                    users1.setNotLogin((byte) 1);
                    users1.setNotMobileLogin(1);
                    count += usersMapper.editUser(users1);
                }
                if (count>0) {
                    toJson.setFlag(0);
                    toJson.setMsg("新建成功");
                }
            }else{
                toJson.setMsg("请输入信息");
            }
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 创建作者：张丽军
     * 方法介绍：左侧部门树根据deptid查询人员
     * @param request
     * @param deptId
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> getLeaveUserByDeptId(HttpServletRequest request,Integer deptId){
        ToJson<HrStaffLeave> toJson = new ToJson<HrStaffLeave>(1, "error");
        try{
            List<HrStaffLeave> list=hrStaffLeaveMapper.getLeaveUserByDeptId(deptId);
            if(list.size()>0){
                toJson.setObj(list);
                toJson.setMsg("ok");
            }else {
                toJson.setMsg("无用户");
            }
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 根据leaveId删除离职人员信息
     * @param leaveId
     * @return
     */
    public ToJson<HrStaffLeave> deleteLeaveInfoByLeaveId(Integer[] leaveId){
        initializeToJson(toJson);
        try {
            if (1 == leaveId.length) {
                hrStaffLeaveMapper.deleteByPrimaryKey(leaveId[0]);
            }else{
                for(Integer ids:leaveId){
                    hrStaffLeaveMapper.deleteByPrimaryKey(ids);
                }
            }
            toJson.setFlag(0);
            toJson.setMsg("删除成功");
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 修改离职人员信息
     * @param hrStaffLeave
     * @param request
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> updateByPrimaryKeySelective(HrStaffLeave hrStaffLeave,HttpServletRequest request){
        initializeToJson(toJson);
        try {
            if (null!=hrStaffLeave.getLeaveId()) {

                //得到用户的userId，来对修改是否黑名单做出限制，设置为只有admin可以修改是否黑名单，但不影响其余项
                Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
                hrStaffLeave.setUpdater(user.getUserId());

                //处理leavePerson
                //把leaveDept和leavePerson后面的逗号去掉
                String[] targetAttributes = {"leaveDept","leavePerson"};
                takeSymbol(hrStaffLeave,targetAttributes,",");

                //附件处理
                if(notNullOrEmpty(hrStaffLeave.getAttachmentName()) && notNullOrEmpty(hrStaffLeave.getAttachmentId())){
                    List<Attachment> attachmentList = GetAttachmentListUtil.
                            returnAttachment(hrStaffLeave.getAttachmentName(),hrStaffLeave.getAttachmentId(),"xoa" + (String) request.
                                    getSession().getAttribute("loginDateSouse"), HRSTAFFLEAVE);//Temp:There's no word of this class in GetAttachmentListUtil.
                    hrStaffLeave.setAttachmentList(attachmentList);
                }

                //执行修改,此方法内含更新时间戳，但设置为不能修改createUserId,createDeptId以及addTime
                int affectedLines = hrStaffLeaveMapper.updateByPrimaryKeySelective(hrStaffLeave);
                if(affectedLines>0){
                    toJson.setFlag(0);
                    toJson.setMsg("修改成功");
                }else{
                    toJson.setMsg("什么也没修改");
                }
            }else{
                toJson.setMsg("请输入修改信息");
            }
        } catch (Exception e) {
           toJson.setMsg("出现异常");
           toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 复职
     * @param request
     * @param hrStaffLeave
     * @param reinstatementWithBLOBs
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> leaveReinstatement(HttpServletRequest request,HrStaffLeave hrStaffLeave,HrStaffReinstatementWithBLOBs reinstatementWithBLOBs){
        initializeToJson(toJson);
        try {
            if (null!=hrStaffLeave.getBlacklist() && null!=hrStaffLeave.getLeavePerson() && null!=hrStaffLeave.getLeaveId() && !hrStaffLeave.getBlacklist()) {
                //处理传入的BLOBs
                //取得当前用户的userId和deptId，存入BLOBs的createUserId和ceateDeptId中
                Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
                reinstatementWithBLOBs.setCreateUserId(user.getUserId());
                reinstatementWithBLOBs.setCreateDeptId(user.getDeptId());

                //处理BLOBs中的reinstatementPerson
                String[] targetAttributes_1 = {"reinstatementPerson"};
                takeSymbol(reinstatementWithBLOBs,targetAttributes_1,",");

                //附件处理
                if (notNullOrEmpty(reinstatementWithBLOBs.getAttachmentName()) && notNullOrEmpty(reinstatementWithBLOBs.getAttachmentId())) {
                    List<Attachment> attachmentList = GetAttachmentListUtil.
                            returnAttachment(reinstatementWithBLOBs.getAttachmentName(), reinstatementWithBLOBs.getAttachmentId(), "xoa" + (String) request.
                                    getSession().getAttribute("loginDateSouse"), REINSTATEMENT);
                    reinstatementWithBLOBs.setAttachmentList(attachmentList);
                }

                //判断和处理4个日期相关的字段为null或空字符串的情况:Is this necessary?Date in mysql has default value.
                String[] targetAttributes_2 = {"reappointmentTimeFact", "reappointmentTimePlan", "applicationDate", "firstSalaryTime"};
                replaceValueToValue(reinstatementWithBLOBs, targetAttributes_2,null,"0000-00-00");
                replaceValueToValue(reinstatementWithBLOBs, targetAttributes_2,"","0000-00-00");

                //处理完毕后插入，此方法内含时间戳
                int count = hrStaffReinstatementMapper.insertSelective(reinstatementWithBLOBs);
                if (count > 0) {
                    String leavePerson = hrStaffLeave.getLeavePerson();

                    //在插入成功的前提下，修改hr_staff_info表中的WORK_STATUS,并盖更新时间戳
                    HrStaffInfo hrStaffInfo = hrStaffInfoMapper.getStaffByUserId(leavePerson);
                    hrStaffInfo.setWorkStatus("01");//01-在职 02-离职
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                    hrStaffInfo.setLastUpdateTime(dateFormat.format(new Date()));
                    count+=hrStaffInfoMapper.updatePersonFile(hrStaffInfo);

                    //然后修改user表中的3个字段,user表没有时间戳
                    Users users = usersMapper.getUsersByuserId(leavePerson);
                    users.setDeptId(hrStaffLeave.getDeptId());//离职状态下deptId = 0。reinstatementBOLBs里面没有deptId,此处的deptId在hrStaffLeave中，与leaveDept区分
                    users.setNotLogin((byte) 2);//OA系统PC端登录权限：1-禁止 2-允许
                    users.setNotMobileLogin(2);//OA系统移动端登录权限：同上
                    count+=usersMapper.editUser(users);

                    //最后删除hr_staff_leave表中信息:Selective.
                    int leaveId = hrStaffLeave.getLeaveId();
                    Integer[] tempArray = {leaveId};
                    deleteLeaveInfoByLeaveId(tempArray);
                    if(null == hrStaffLeaveMapper.selectByLeaveId(leaveId)){
                        count++;
                    }

                    if (count == 4) {//Maybe can loose condition.
                        toJson.setFlag(0);
                        toJson.setMsg("新建复职信息成功");
                    } else {
                        toJson.setFlag(0);
                        toJson.setMsg("相关信息修改失败");
                    }
                } else {
                    toJson.setMsg("新建复职信息失败");
                }
            } else {
                toJson.setMsg("请输入复职信息");
            }
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 根据leaveId查询详细信息
     * @param leaveId
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> leaveDetails(Integer leaveId,HttpServletRequest request){
        initializeToJson(toJson);
        try {
            HrStaffLeave hrStaffLeave = hrStaffLeaveMapper.selectByLeaveId(leaveId);//此处设置为，如果在user表中没有相关信息，则其他信息也不予显示
            //附件处理
            List<Attachment> attachmentList = new ArrayList<Attachment>();
            if (notNullOrEmpty(hrStaffLeave.getAttachmentName())&&notNullOrEmpty(hrStaffLeave.getAttachmentId())) {
                 attachmentList = GetAttachmentListUtil.
                        returnAttachment(hrStaffLeave.getAttachmentName(), hrStaffLeave.getAttachmentId(), "xoa" + (String) request.
                                getSession().getAttribute("loginDateSouse"), HRSTAFFLEAVE);
            }
            hrStaffLeave.setAttachmentList(attachmentList);
            handleHrStaffLeaveOutput(hrStaffLeave);
            toJson.setFlag(0);
            toJson.setMsg("查询成功");
            toJson.setObject(hrStaffLeave);
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 查询黑名单，需要一定的权限
     * @param request
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> leaveBlackList(HttpServletRequest request){
        initializeToJson(toJson);
        try {

           /*//分页
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);
            pageParams.setPageSize(pageSize);
            pageParams.setPage(page);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("page",pageParams);*/

            //备选权限限制:行政级别
           /* Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
            HrStaffInfo hrStaffInfo = hrStaffInfoMapper.getStaffByUserId(user.getUserId());
            String adminLevel = hrStaffInfo.getAdministrationLevel();
            String[] allowLevels = {""};
            if(isIn(allowLevels,adminLevel))*/

            //得到用户的userId，来对查询黑名单做出限制，设置为只有admin可以查询黑名单
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
            String userId = user.getUserId();

            List<HrStaffLeave> leaveInfoList = new ArrayList<HrStaffLeave>();
            if ("admin".equals(userId)) {
                //根据黑名单查询
                leaveInfoList = hrStaffLeaveMapper.selectByIsBlackList();
            }
            handleHrStaffLeaveOutput(leaveInfoList);

            toJson.setFlag(0);
            toJson.setMsg("查询成功");
            toJson.setObj(leaveInfoList);
            toJson.setTotleNum(hrStaffLeaveMapper.selectCountBlackList());
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 查询本月离职人员信息
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> leaveThisMonth(){
        initializeToJson(toJson);
        try {

             /*//分页
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);
            pageParams.setPageSize(pageSize);
            pageParams.setPage(page);

            Map<String,Object> map = new HashMap<String, Object>();
            map.put("page",pageParams);
            map.put("thisMonth",thisMonth);*/

            //获取当前月份
            Date nowDate = new Date();
            SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
            String thisMonth = monthFormat.format(nowDate);

            //根据当前月份进行查询
            List<HrStaffLeave> leaveInfoList = hrStaffLeaveMapper.selectThisMonth(thisMonth);
            handleHrStaffLeaveOutput(leaveInfoList);

            toJson.setFlag(0);
            toJson.setMsg("查询成功");
            toJson.setObj(leaveInfoList);
            toJson.setTotleNum(hrStaffLeaveMapper.selectCountThisMonth(thisMonth));
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇 2018/7/31
     * 条件查询
     * @param leavePerson
     * @param quitType
     * @param deptId
     * @param quitTimePlanStart
     * @param quitTimePlanEnd
     * @param quitTimeFactStart
     * @param quitTimeFactEnd
     * @param quitReason
     * @param despacho
     * @param useFlag
     * @param pageSize
     * @param page
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> leaveConditionQuery(String leavePerson,String quitType,String deptId,String quitTimePlanStart,String quitTimePlanEnd,String quitTimeFactStart,String quitTimeFactEnd,String quitReason,String despacho,Boolean useFlag,Integer pageSize,Integer page){
        initializeToJson(toJson);
        try {

            //分页
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);
            pageParams.setPageSize(pageSize);
            pageParams.setPage(page);

            //把leavePerson和leaveDept后面的逗号去掉
            if(null!=leavePerson && leavePerson.contains(",")){
                String[] tempArray = leavePerson.split(",");
                leavePerson = tempArray[0];
            }
            if(null!=deptId && deptId.contains(",")){
                String[] tempArray = deptId.split(",");
                deptId = tempArray[0];
            }

            //配置条件参数集合
            Map<String,Object> parameterMap = new HashMap<String,Object>();
            parameterMap.put("leavePerson",leavePerson);
            parameterMap.put("quitType",quitType);
            parameterMap.put("deptId",deptId);
            parameterMap.put("quitTimePlanStart",quitTimePlanStart);
            parameterMap.put("quitTimePlanEnd",quitTimePlanEnd);
            parameterMap.put("quitTimeFactStart",quitTimeFactStart);
            parameterMap.put("quitTimeFactEnd",quitTimeFactEnd);
            parameterMap.put("quitReason",quitReason);
            parameterMap.put("despacho",despacho);
            parameterMap.put("page",pageParams);

            List<HrStaffLeave> leaveInfoList = new ArrayList<HrStaffLeave>();

            if(notNullOrEmpty(leavePerson)||notNullOrEmpty(quitType)||notNullOrEmpty(deptId)||notNullOrEmpty(quitTimePlanStart)||notNullOrEmpty(quitTimePlanEnd)||notNullOrEmpty(quitTimeFactStart)||notNullOrEmpty(quitTimeFactEnd)||notNullOrEmpty(quitReason)||notNullOrEmpty(despacho)) {
                //查询
                leaveInfoList = hrStaffLeaveMapper.selectByConditions(parameterMap);
            }else {
                leaveInfoList=hrStaffLeaveMapper.selectQuery(parameterMap);

            }
            handleHrStaffLeaveOutput(leaveInfoList);

            toJson.setFlag(0);
            toJson.setMsg("查询成功");
            toJson.setObj(leaveInfoList);
            toJson.setTotleNum(hrStaffLeaveMapper.selectCountByConditions(parameterMap));
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 列表查询
     * @param useFlag
     * @param pageSize
     * @param page
     * @return
     */
    public ToJson<HrStaffLeave> leaveQuery(Boolean useFlag,Integer pageSize,Integer page,String leavePerson){
        initializeToJson(toJson);
        try {
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);
            pageParams.setPageSize(pageSize);
            pageParams.setPage(page);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("page",pageParams);
            map.put("leavePerson",leavePerson);

            List<HrStaffLeave> list = hrStaffLeaveMapper.selectQuery(map);
            handleHrStaffLeaveOutput(list);
            
            toJson.setFlag(0);
            toJson.setMsg("查询成功");
            toJson.setObj(list);
            toJson.setTotleNum(hrStaffLeaveMapper.selectCount());
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 导入离职人员信息
     * @param file
     * @param request
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> importLeaveInfo(MultipartFile file,HttpServletRequest request){
        initializeToJson(toJson);
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
                StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
            // 判断是否为空文件
            if (file.isEmpty()) {
                toJson.setMsg("请上传文件");
                return toJson;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrStaffLeave hrStaffLeave = null;
                    for (int i = 3; i <= lastRowNum; i++) {
                        hrStaffLeave = new HrStaffLeave();
                        row = sheetObj.getRow(i);
                        if (null!=row) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                String cellValue = null;
                                if (null == cell){
                                    continue;
                                } else {
                                    cellValue = cell.getStringCellValue();
                                }
                                if (null!=cellValue) {
                                    switch (j) {
                                        case 0:
                                            //姓名
                                            Users users = usersMapper.getUserByUserName(cellValue);
                                            if (null!=users && null!=users.getUserId()) {
                                                hrStaffLeave.setLeavePerson(users.getUserId());
                                           /* } else {
                                                toJson.setMsg("查无此人！");
                                                return toJson;*/
                                            }
                                            break;
                                        case 1:
                                            //离职类型
                                            String quitType = null;
                                            switch (cellValue){
                                                case "辞职":
                                                    quitType = "1";
                                                    break;
                                                case "离休":
                                                    quitType = "2";
                                                    break;
                                                case "退休":
                                                    quitType = "3";
                                                    break;
                                                case "借调":
                                                    quitType = "4";
                                                    break;
                                                   /* default:
                                                        toJson.setMsg("不存在此离职类型！");
                                                        return toJson;*/
                                            }
                                            hrStaffLeave.setQuitType(quitType);
                                            break;
                                        case 2:
                                            //担任职务
                                            int postId = 0;
                                            if (null == hrStaffLeaveMapper||null == hrStaffLeaveMapper.getPositionByPostName(cellValue)){
                                                break;
                                            } else {
                                                postId = hrStaffLeaveMapper.getPositionByPostName(cellValue);
                                            }
                                            if (postId>0) {
                                                hrStaffLeave.setPosition(String.valueOf(postId));
                                           /* } else {
                                                toJson.setMsg("请输入正确的职务名称！");
                                                return toJson;*/
                                            }
                                            break;
                                        case 3:
                                            //离职部门
                                            int deptId = 0;
                                            if (null == hrStaffLeaveMapper||null == hrStaffLeaveMapper.getLeaveDeptByDeptName(cellValue)){
                                                break;  
                                            } else {    
                                                deptId = hrStaffLeaveMapper.getLeaveDeptByDeptName(cellValue);
                                            }           
                                            if (deptId>0) {
                                                hrStaffLeave.setLeaveDept(String.valueOf(deptId));
                                          /*  } else {
                                                toJson.setMsg("请输入正确的部门名称！");
                                                return toJson;*/
                                            }
                                            break;
                                        case 4:
                                            //申请日期
                                            hrStaffLeave.setApplicationDate(cellValue);
                                            break;
                                        case 5:
                                            //拟离职日期
                                            hrStaffLeave.setQuitTimePlan(cellValue);
                                            break;
                                        case 6:
                                            //实际离职日期
                                            hrStaffLeave.setQuitTimeFact(cellValue);
                                            break;
                                        case 7:
                                            //工资截止日期
                                            hrStaffLeave.setLastSalaryTime(cellValue);
                                            break;
                                        case 8:
                                            //去向
                                            hrStaffLeave.setTrace(cellValue);
                                            break;
                                        case 9:
                                            //离职手续办理
                                            hrStaffLeave.setDespacho(cellValue);
                                            break;
                                        case 10:
                                            //离职原因
                                            if (!"".equals(cellValue)) {
                                                hrStaffLeave.setQuitReason(cellValue);
                                        /*    } else {
                                                toJson.setMsg("请填写离职原因！");
                                                return toJson;*/
                                            }
                                            break;
                                        case 11:
                                            //备注
                                            hrStaffLeave.setRemark(cellValue);
                                            break;
                                        case 12:
                                            //离职当月薪资
                                            hrStaffLeave.setSalary(Integer.valueOf(cellValue));
                                            break;
                                        case 13:
                                            //身份证号
                                            hrStaffLeave.setStaffCardNo(cellValue);
                                            break;
                                        case 14:
                                            //批示人
                                            hrStaffLeave.setDespachoPerson(cellValue);
                                            break;
                                        case 15:
                                            //物品交接情况
                                            hrStaffLeave.setMaterialsCondition(cellValue);
                                            break;
                                    }
                                }
                            }
                            if (null!=hrStaffLeave.getLeavePerson()) {

                                //存createUserId和createDeptId
                                Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
                                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
                                hrStaffLeave.setCreateUserId(user.getUserId());
                                hrStaffLeave.setCreateDeptId(user.getDeptId());

                                //由于数据库中字段都不能为空，所以要做一下判断和处理
                                handleHrStaffLeaveInput(hrStaffLeave);

                                /*HrStaffLeave hrStaffLeaveInDataBase = hrStaffLeaveMapper.selectTheSame(hrStaffLeave);
                                String leavePerson = hrStaffLeave.getLeavePerson();
                                String leavePersonInDataBase = hrStaffLeaveInDataBase.getLeavePerson();
                                String staffCardNo = hrStaffLeave.getStaffCardNo();
                                String staffCardNoInDataBase = hrStaffLeaveInDataBase.getStaffCardNo();*/
                                //执行导入
                                //if (leavePerson.equals(leavePersonInDataBase)&&staffCardNo.equals(staffCardNoInDataBase)) {
                                    hrStaffLeaveMapper.addLeaveInfor(hrStaffLeave);
                                //}

                                //修改信息表
                                HrStaffInfo hrStaffInfo = hrStaffInfoMapper.getStaffByUserId(hrStaffLeave.getLeavePerson());
                                if (null!=hrStaffInfo) {
                                    hrStaffInfo.setWorkStatus("02");
                                    if (!"0000-00-00".equals(hrStaffLeave.getQuitTimeFact())) {
                                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                                        int year= DateCompute.workAge(sdf.parse(hrStaffLeave.getQuitTimeFact()),sdf.parse(hrStaffInfo.getJobBeginning()));
                                        hrStaffInfo.setJobAge(String.valueOf(year));
                                    }
                                    hrStaffInfoMapper.updatePersonFile(hrStaffInfo);

                                    //将原部门id(leaveDept)存入hr_staff_info表中的DEPT_ID字段中
                                    hrStaffInfo.setDeptId(Integer.valueOf(hrStaffLeave.getLeaveDept()));
                                    hrStaffLeaveMapper.updateHrStaffInfoDeptId(hrStaffInfo);
                                }

                                //修改用户表
                                Users users1 = usersMapper.getUsersByuserId(hrStaffLeave.getLeavePerson());//先将要修改的用户信息查询出来，将部门编号改为0，0：代表用户离职
                                if (null!=users1) {
                                    users1.setDeptId(0);
                                    users1.setNotLogin((byte) 1);
                                    users1.setNotMobileLogin(1);
                                    usersMapper.editUser(users1);
                                }
                            }
                        }
                    }
                }
            }
            toJson.setFlag(0);
            toJson.setMsg("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setMsg("出现异常");
        }
        return toJson;
    }

    /**
     * 郅浩宇
     * 导出
     * @param
     * @param response
     * @param request
     * @return
     */
    @Override
    public ToJson<HrStaffLeave> exportLeaveInfo(String leavePerson,String quitType,String deptId,String quitTimePlanStart,String quitTimePlanEnd,String quitTimeFactStart,String quitTimeFactEnd,String quitReason,String despacho,Boolean useFlag,Integer pageSize,Integer page, HttpServletResponse response,HttpServletRequest request){
        //todo:Test.
        initializeToJson(toJson);
        try {
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);
            pageParams.setPageSize(pageSize);
            pageParams.setPage(page);

            //把leavePerson和leaveDept后面的逗号去掉
            if(null!=leavePerson && leavePerson.contains(",")){
                String[] tempArray = leavePerson.split(",");
                leavePerson = tempArray[0];
            }
            if(null!=deptId && deptId.contains(",")){
                String[] tempArray = deptId.split(",");
                deptId = tempArray[0];
            }

            //配置条件参数集合
            Map<String,Object> parameterMap = new HashMap<String,Object>();
            parameterMap.put("leavePerson",leavePerson);
            parameterMap.put("quitType",quitType);
            parameterMap.put("deptId",deptId);
            parameterMap.put("quitTimePlanStart",quitTimePlanStart);
            parameterMap.put("quitTimePlanEnd",quitTimePlanEnd);
            parameterMap.put("quitTimeFactStart",quitTimeFactStart);
            parameterMap.put("quitTimeFactEnd",quitTimeFactEnd);
            parameterMap.put("quitReason",quitReason);
            parameterMap.put("despacho",despacho);
            parameterMap.put("page",pageParams);

            List<HrStaffLeave> leaveInfoList = new ArrayList<HrStaffLeave>();

            if(notNullOrEmpty(leavePerson)||notNullOrEmpty(quitType)||notNullOrEmpty(deptId)||notNullOrEmpty(quitTimePlanStart)||notNullOrEmpty(quitTimePlanEnd)||notNullOrEmpty(quitTimeFactStart)||notNullOrEmpty(quitTimeFactEnd)||notNullOrEmpty(quitReason)||notNullOrEmpty(despacho)) {
                //查询
                leaveInfoList = hrStaffLeaveMapper.selectByConditions(parameterMap);
            }else {
                leaveInfoList=hrStaffLeaveMapper.selectQuery(parameterMap);
            }
            for (HrStaffLeave hrStaffLeave:leaveInfoList){
                if (hrStaffLeave.getQuitType().equals("1")){
                    hrStaffLeave.setQuitType("辞职");
                }else if (hrStaffLeave.getQuitType().equals("2")){
                    hrStaffLeave.setQuitType("离休");
                }else if (hrStaffLeave.getQuitType().equals("3")){
                    hrStaffLeave.setQuitType("退休");
                }else if(hrStaffLeave.getQuitType().equals("4")){
                    hrStaffLeave.setQuitType("借调");
                }else{
                    hrStaffLeave.setQuitType("未知");
                }
            }

            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("离职人员信息表", 16);
            String[] secondTitles = {"姓名","离职类型","担任职务","离职部门","申请日期","拟离职日期","实际离职日期","工资截止日期","去向","离职手续办理","离职原因","备注","离职当月薪资","身份证号","批示人","物品交接情况"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
            //String[] beanProperty = {"leavePerson","quitType","position","leaveDept","applicationDate","quitTimePlan","quitTimeFact","lastSalaryTime","trace","despacho","quitReason","remark","salary","staffCardNo","despachoPerson","materialsCondition"};
            String[] beanProperty = {"userName","quitType","position","deptName","applicationDate","quitTimePlan","quitTimeFact","lastSalaryTime","trace","despacho","quitReason","remark","salary","staffCardNo","despachoPerson","materialsCondition"};
            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, leaveInfoList, beanProperty);
            OutputStream outputStream = response.getOutputStream();
            String filename = "离职人员信息表.xls";//考虑多语言
            filename = FileUtils.encodeDownloadFilename(filename,
                    request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + filename);
            workbook.write(outputStream);
            outputStream.close();
            toJson.setFlag(0);
            toJson.setMsg("导出成功");
        } catch (Exception e) {
            toJson.setMsg("出现异常");
            toJson.setObject(e);
        }
        return toJson;
    }

    /**
     * 创建者：戚中校
     * 方法作用：根据条件查询数量
     * @param
     * @param deptId(传入的多个部门的编号)
     * @return 返回的json字符串中  nums是返回的结果的数量
     *
     */

    public ToJson<HrStaffLeave> selectNumByCon(HrStaffLeave record, Integer[] deptId) {
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId!=null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<HrStaffLeave> list = hrStaffLeaveMapper.selectNumByCon(map);

            for(HrStaffLeave hrStaffLeave:list){
                if(hrStaffLeave.getQuitType()!=null){
                    HrCode hr_staff_contract1 = hrCodeMapper.selectCode("HR_STAFF_LEAVE",hrStaffLeave.getQuitType());
                    if (hr_staff_contract1!=null) {
                        hrStaffLeave.setQuitTypeName(hr_staff_contract1.getCodeName());
                    } else {
                        hrStaffLeave.setQuitTypeName("其它");
                    }
                }

                if(hrStaffLeave.getQuitTimeFact()!=null){
                    String year = hrStaffLeave.getQuitTimeFact().toString().substring(0,4);
                    hrStaffLeave.setQuitTimeFactYear(year);
                }
            }
            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    //在传入数据库前，对HrStaffLeave的对象实例进行处理
    private static void handleHrStaffLeaveInput(HrStaffLeave hrStaffLeave){
        //当日期的相关属性为null或空字符串时，替换为"0000-00-00"
        String[] targetAttributes_1 = {"quitTimePlan","quitTimeFact","lastSalaryTime","applicationDate"};
        replaceValueToValue(hrStaffLeave,targetAttributes_1,null,"0000-00-00");
        replaceValueToValue(hrStaffLeave,targetAttributes_1,"","0000-00-00");
        //部分属性为null时替换为空字符串
        String[] targetAttributes_2 = {"quitType","quitReason","trace","remark","materialsCondition","despacho","despachoPerson","position","attachmentId","attachmentName"};
        replaceValueToValue(hrStaffLeave,targetAttributes_2,null,"");
        //是否允许复职默认允许（0-允许，1-禁止）
        String[] targetAttributes_3 = {"isReinstatement"};
        replaceValueToValue(hrStaffLeave,targetAttributes_3,null,0);
        //默认不是黑名单
        if (!notNullOrEmpty(hrStaffLeave.getBlacklist())) {
            hrStaffLeave.setIsBlacklist(false);
        }
        //把leaveDept和leavePerson后面的逗号去掉
        String[] targetAttributes = {"leaveDept","leavePerson"};
        takeSymbol(hrStaffLeave,targetAttributes,",");
    }

    //在输出前对数据库中的字段进行处理
    private static void handleHrStaffLeaveOutput(List<HrStaffLeave> list){
        String[] tempArray_1 = {"deptName","userName","postName","quitTimeFact","quitTimePlan","lastSalaryTime"};
        String[] tempArray_2 = {"salary"};
        for(HrStaffLeave hrStaffLeave:list){
            replaceValueToValue(hrStaffLeave,tempArray_1,null,"");
            replaceValueToValue(hrStaffLeave,tempArray_2,null,0);
            String quitType = hrStaffLeave.getQuitType();
            setQuitTypeName(quitType,hrStaffLeave);
        }
    }

    //针对查询详情接口，在输出前对数据库中的字段进行处理
    private static void handleHrStaffLeaveOutput(HrStaffLeave hrStaffLeave){
        String[] tempArray_1 = {"deptName","userName","postName","quitTimeFact","quitTimePlan","lastSalaryTime","applicationDate","trace","despacho","quitReason","remark","addTime","lastUpdateTime","leavePerson"};
        String[] tempArray_2 = {"salary"};
        replaceValueToValue(hrStaffLeave,tempArray_1,null,"");
        replaceValueToValue(hrStaffLeave,tempArray_2,null,0);
        String quitType = hrStaffLeave.getQuitType();
        setQuitTypeName(quitType,hrStaffLeave);
    }

    //将数据库中的离职类型字段替换成具体的离职类型
    private static void setQuitTypeName(String quitType,HrStaffLeave hrStaffLeave){
        switch (quitType){
            case "1":
                hrStaffLeave.setQuitType("辞职");
                break;
            case "2":
                hrStaffLeave.setQuitType("离休");
                break;
            case "3":
                hrStaffLeave.setQuitType("退休");
                break;
            case "4":
                hrStaffLeave.setQuitType("借调");
                break;
            default:
                hrStaffLeave.setQuitType("未知");
        }
    }

    //将对象实例的指定属性值替换为另一个值
    private static void replaceValueToValue(Object object,String[] targetAttributes,Object pastValue,Object valueForReplace){
        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field attribute:fields){
                attribute.setAccessible(true);
                String attributeName = attribute.getName();
                if(isIn(targetAttributes,attributeName)){
                    if (attribute.get(object) == pastValue){
                        attribute.set(object,valueForReplace);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //去掉某对象实例的目标属性的字符串里的符号和它后面的内容
    private static void takeSymbol(Object object,String[] targetAttributes,String regex){
        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for(Field attribute:fields){
                attribute.setAccessible(true);
                String attributeName = attribute.getName();
                if(isIn(targetAttributes,attributeName)){
                    if (null!=attribute.get(object)) {
                        String attributeStringValue = null;
                        attributeStringValue = attribute.get(object).toString();
                        if(null!=attributeStringValue && attributeStringValue.contains(regex)){
                            String[] tempArray = attributeStringValue.split(regex);
                            attribute.set(object,tempArray[0]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //判断字符串对象是否在字符串数组中
    private static boolean isIn(String[] stringArray,String string){
        for(String str:stringArray){
            if(str.equals(string)){
                return true;
            }
        }
        return false;
    }

    //使用同一个ToJson对象，需要初始化ToJson,默认的Flag值为1，即false
    private static void initializeToJson(ToJson<HrStaffLeave> toJson){
        toJson.setFlag(1);
        toJson.setMsg(null);
        toJson.setObj(null);
        toJson.setObject(null);
        toJson.setTotleNum(null);
    }

    //判断对象是否为null或空字符串
    private static boolean notNullOrEmpty(Object object){
        try {
            return null!=object && !"".equals(object.toString().trim());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public ToJson<HrStaffLeave> getByStaffName(String staffName, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<HrStaffLeave> json=new ToJson<HrStaffLeave>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<HrStaffLeave> list= hrStaffLeaveMapper.getByStaffName(map);
            if(list.size()>0){
                for(HrStaffLeave leave:list) {
                    if (leave.getLeavePerson() != null) {
                        Users user = usersMapper.findUsersByuserId(leave.getLeavePerson()); //根据 id 找名字
                        if (user != null) {
                            leave.setLeavePerson(user.getUserName());
                        } else {
                            leave.setLeavePerson(" ");
                        }
                        //离职类型
                        HrCode hr_staff_contract2 = hrCodeMapper.selectCode("HR_STAFF_LEAVE",leave.getQuitType());
                        if (hr_staff_contract2 != null) {
                            leave.setQuitType(hr_staff_contract2.getCodeName());
                        } else {
                            leave.setQuitType(" ");
                        }
                    }
                }
                json.setObj(list);
            }
            json.setTotleNum(hrStaffLeaveMapper.getByStaffNameCount(staffName));
            json.setFlag(0);
            json.setMsg("true");
        }catch (Exception e){
            e.printStackTrace();;
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    public static boolean isValidDate(String str) {
        boolean convertSuccess=true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
             format.setLenient(false);
             format.parse(str);
        } catch (ParseException e) {
             // e.printStackTrace();
             // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
             convertSuccess=false;
        }
        return convertSuccess;
    }
}
